package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.Appointment;
import cn.wolfcode.car.business.domain.Statement;
import cn.wolfcode.car.business.domain.StatementItem;
import cn.wolfcode.car.business.mapper.AppointmentMapper;
import cn.wolfcode.car.business.mapper.StatementItemMapper;
import cn.wolfcode.car.business.mapper.StatementMapper;

import cn.wolfcode.car.business.query.StatementQuery;
import cn.wolfcode.car.business.service.IStatementServicePlus;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.common.util.Convert;
import cn.wolfcode.car.shiro.ShiroUtils;
import com.alibaba.druid.support.spring.stat.annotation.Stat;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import net.bytebuddy.asm.Advice;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class StatementServiceImplPlus extends ServiceImpl<StatementMapper,Statement> implements IStatementServicePlus {

    @Autowired
    private AppointmentMapper appointmentMapper;
    @Autowired
    private StatementMapper statementMapper;
    @Autowired
    private StatementItemMapper statementItemMapper;


    @Override
    public TablePageInfo<Statement> query(StatementQuery qo) {
        IPage<Statement> page = new Page<>(qo.getPageNum(),qo.getPageSize());
        QueryWrapper<Statement> wrapper = new QueryWrapper<>();
        wrapper.like(StringUtils.hasText(qo.getCustomerName()), "customer_name",qo.getCustomerName())
                .like(StringUtils.hasText(qo.getCustomerPhone()),"customer_phone",qo.getCustomerPhone())
                .like(StringUtils.hasText(qo.getLicensePlate()),"license_plate",qo.getLicensePlate());
        return new TablePageInfo<Statement>(super.page(page,wrapper));
    }


   @Override
    public Statement generateStatement(Long appointmentId) {
        //通过id查询预约对象，判断其状态
        Appointment appointment = appointmentMapper.selectById(appointmentId);
        Integer status = appointment.getStatus();
        if(!(Appointment.STATUS_ARRIVAL.equals(status) || Appointment.STATUS_SETTLE.equals(status))){
            throw new BusinessException("只有结算单和到店状态才可点击结算单按钮");
        }
       //根据预约单ID去结算单表中查询是否已经有记录
       //Statement statement = statementMapper.queryAppointmentId(appointmentId);
       QueryWrapper<Statement> wrapper = new QueryWrapper<>();
        wrapper.eq("appointment_id",appointmentId);
       Statement statement = statementMapper.selectOne(wrapper);

       //如果不能找到,说明之前没有生成过结算单,把预约单信息封装成结算单对象,并插入到结算单中
        if(statement == null){
            statement = new Statement();
            statement.setCreateTime(new Date());
            statement.setActualArrivalTime(appointment.getActualArrivalTime());//实际到店时间
            statement.setCarSeries(appointment.getCarSeries());//汽车类型
            statement.setCustomerName(appointment.getCustomerName());//客户名称
            statement.setLicensePlate(appointment.getLicensePlate());//车牌号码
            statement.setAppointmentId(appointment.getId());//预约单ID
            statement.setServiceType(appointment.getServiceType().longValue());//服务类型
            statement.setCustomerPhone(appointment.getCustomerPhone());//用户联系方式
            statementMapper.insert(statement);
            //保存成功后把预约单状态修改成结算单生成
            UpdateWrapper<Appointment> wrapper1 = new UpdateWrapper<>();
            wrapper1.eq("id", appointmentId);
            wrapper1.set("status",Appointment.STATUS_SETTLE);
        }
        return statement;
    }

    @Override
    public void exportOP(Long statementId, HttpServletResponse response) throws IOException {
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("结算单明细列表");
        Row row1 = sheet.createRow(0);
        row1.createCell(0).setCellValue("服务项名称");
        row1.createCell(1).setCellValue("服务项价格");
        row1.createCell(2).setCellValue("购买数量");


        QueryWrapper<StatementItem> wrapper = new QueryWrapper<>();
        wrapper.select("item_name","item_price","item_quantity");
        wrapper.eq("statement_id",statementId);
        List<StatementItem> items = statementItemMapper.selectList(wrapper);

        for (int i = 0; i < items.size(); i++) {
            StatementItem statementItem = items.get(i);
            Row row = sheet.createRow(i + 1);
            row.createCell(0).setCellValue(statementItem.getItemName());
            row.createCell(1).setCellValue(String.valueOf(statementItem.getItemPrice()));
            row.createCell(2).setCellValue(String.valueOf(statementItem.getItemQuantity()));
        }
        ServletOutputStream out = response.getOutputStream();
        workbook.write(out);
        out.close();
        workbook.close();
    }
}
